// pages/login_phone/login_phone.js
import {
  $await
} from '../../utils/util';
import {
  loginAPI
} from '../../api/public/index'
var app = getApp()
Page({

  /**
   * 页面的初始数据
   */
  data: {
    time: 60,
    sendMg: '获取验证码',
    sendNum: 0,
    isLogin: false,
    phone: '',
    codeColor:''
  },

  /**
   * 生命周期函数--监听页面加载
   */
  onLoad: function (options) {
    
    // if (options.isBack) {
    //   this.setData({
    //     isBack : true
    //   })
    // }
  },

  /**
   * 生命周期函数--监听页面初次渲染完成
   */
  onReady: function () {

  },

  /**
   * 生命周期函数--监听页面显示
   */
  onShow: function () {},

  /**
   * 生命周期函数--监听页面隐藏
   */
  onHide: function () {

  },

  /**
   * 生命周期函数--监听页面卸载
   */
  onUnload: function () {

  },

  /**
   * 页面相关事件处理函数--监听用户下拉动作
   */
  onPullDownRefresh: function () {

  },

  /**
   * 页面上拉触底事件的处理函数
   */
  onReachBottom: function () {

  },

  /**
   * 用户点击右上角分享
   */
  onShareAppMessage: function () {

  },
  closePhone() {
    this.setData({
      phone: ''
    })

  },
  codes(e) {
    let code = e.detail.value;
    this.setData({
      code,
      isLogin: true
    })
  },
  phone(e) {
    let value = e.detail.value,
      that = this;
    this.setData({
      phone: value
    })
  },
  async getCode() {
    var that = this,
      reg = /^1\d{10}$/;
    if (this.data.time != 60) {
      return false;
    }
    if (!reg.test(this.data.phone)) {
      wx.showToast({
        title: '请输入正确的手机号!',
        icon: 'none',
        duration: 2000
      })
      return;
    }
    let [err, res] = await $await(loginAPI.sendCode({
      mobile: that.data.phone
    }))
    if (res) {
      that.sendCode()
    }

  },

  sendCode() {
    var that = this;
    var times = setInterval(function () {
      if (that.data.time == 0) {
        clearInterval(times);
        that.setData({
          sendMg: "获取验证码",
          sendNum: 0,
          time: 60
        })
        return false;
      } else {
        that.data.time--;
        // console.log(that.data.time)
        that.setData({
          time: that.data.time,
          sendMg: that.data.time + "后重新获取",
          sendNum: 1
        })
      }
    }, 1000)
  },


  getCodeValue() {
    if (this.data.phone && this.data.code) {
      this.setData({
        isLogin: true
      })
    }
    if(/^1\d{10}$/.test(this.data.phone)){
      this.setData({codeColor:'#FC404A'})
    }else{
      this.setData({codeColor:''})
    }
  },
  async login() {
    let that = this;
    let [err, res] = await $await(loginAPI.login({
      mobile: that.data.phone,
      code : this.data.code
    }))
    if (res) {
      console.log(res)
      wx.setStorageSync('userInfo', res)
      let path = getCurrentPages()
      wx.redirectTo({
        url: path[path.length-2].route
      })
    //  if (this.data.isBack) {
      //  wx.reLaunch({
      //    url: '/pages/my/my',
      //   })
    //   } else {
    //    wx.navigateBack()
    //  }
    }
  }
})